package com.plug.controller.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by slaye on 2016/12/22.
 */
public class AbstractController {
//    static final Logger log = Logger.getLogger(AbstractController.class);
    private Logger log = LoggerFactory.getLogger(getClass());

    /** 基于@ExceptionHandler异常处理 */
    //(value = { BusinessException.class, ParameterException.class, Exception.class})
    @ExceptionHandler
    public String exception(HttpServletRequest request, HttpServletResponse response, Exception e) {

        e.printStackTrace();
        log.error("error", e);
        //如果是json格式的ajax请求
        if (request.getHeader("accept").indexOf("application/json") > -1
                || (request.getHeader("X-Requested-With")!= null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {
            response.setStatus(500);
            response.setContentType("application/json;charset=utf-8");
            try {
                PrintWriter writer = response.getWriter();
                writer.write(e.getMessage());
                writer.flush();
            } catch (IOException e1) {
                e1.printStackTrace();
                log.error("error1", e);
            }
            return null;
        }
        else{//如果是普通请求
            request.setAttribute("msg", e.getMessage());
            // 根据不同的异常类型可以返回不同界面
            if(e instanceof Exception)
                return "error/index_error";
            else
                return "error/index_error";
        }
    }

    /**
     * 返回json
     *
     * @param response
     * @param jsons
     */
    protected void returnJson(HttpServletResponse response, final String jsons) {
        response.setCharacterEncoding("utf-8");
        response.addHeader("expires", "0");
        response.addHeader("Cache-Control", "no-cache");
        response.setContentType("text/html;charset=utf-8"); // 兼容ff
        try {
            response.getWriter().write(jsons);
        } catch (final Exception e) {
            e.printStackTrace();
            log.error("AJax请求，返回JSON出错：",e);
        }
    }

}
